// pages/settings/index.js
const app = getApp();
const domain = app.globalData.domain
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    levelVis: false,
    levelOptions: [{
        label: 'L1',
        value: 'L1'
      },
      {
        label: 'L2',
        value: 'L2'
      },
      {
        label: 'L3',
        value: 'L3'
      },
    ],
    currentLevel: null,
    configs: [],
    zhibiaoVis: false,
    currentZhibiaoInfo: null,
    zhibiaoOptions: [],
    currentZhibiao: null,
    currentIndex: null,
    currentTiaojianInfo: null,
    tiaojianVis: false,
    tiaojianOptions: [{
        label: '等于',
        value: 'eq'
      }, {
        label: '大于',
        value: 'gt'
      }, {
        label: '小于',
        value: 'lt'
      }, {
        label: '恒值',
        value: 'nchg'
      }
      // {
      //   label: '区间',
      //   value: '区间'
      // },
      // {
      //   label: '保持',
      //   value: 'eq'
      // }
    ]
  },
  onBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  initZhibiao(options) {
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: `${domain}/admin-api/smc/scene/metric?sceneId=${options.id}`,
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        wx.hideLoading()
        if (res?.data?.error === "Unauthorized") {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log(res)
        const zhibiaoMap = {}
        const kongzhiduixiangMap = {}

        const kongzhiduixiangOptions = res?.data?.data?.list?.filter(item => item.ctrlAble === 1)?.map(item => {
          kongzhiduixiangMap[item.id] = item.name
          return {
            label: item.name,
            value: item.id
          }
        })
        const zhibiaoOptions = res?.data?.data?.list?.map(item => {
          zhibiaoMap[item.id] = item.name
          return {
            label: item.name,
            value: item.id
          }
        })
        this.setData({
          kongzhiduixiangOptions,
          kongzhiduixiangMap,
          zhibiaoOptions,
          zhibiaoMap
          // posName,
        }, () => {
          this.init(options)
        })
      }
    })
  },
  openZhibiao(e) {
    this.setData({
      currentZhibiaoInfo: e.currentTarget.dataset,
      zhibiaoVis: true
    })
  },
  openTiaojian(e) {
    this.setData({
      currentTiaojianInfo: e.currentTarget.dataset,
      tiaojianVis: true
    })
  },
  openLevel(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setData({
      currentIndex: index,
      levelVis: true
    })
  },
  onLevelConfirm(e) {
    const nConfigs = this.data.configs;
    nConfigs[this.data.currentIndex].level = e.detail.value?.[0]
    this.setData({
      configs: nConfigs
    })
  },
  onTiaojiao1Confirm(e) {
    const nConfigs = this.data.configs;
    const {
      pindex,
      index
    } = this.data.currentTiaojianInfo
    nConfigs[pindex].conditions[index][1] = e.detail.value?.[0]
    this.setData({
      configs: nConfigs
    })
  },
  onZhibiaoConfirm(e) {
    const nConfigs = this.data.configs;
    const {
      pindex,
      index
    } = this.data.currentZhibiaoInfo
    nConfigs[pindex].conditions[index][0] = e.detail.value?.[0]
    this.setData({
      configs: nConfigs
    })
  },
  changeValue(e) {
    const value = e.detail.value
    console.log(e)
    const nConfigs = this.data.configs;
    const {
      pindex,
      index
    } = e.currentTarget.dataset
    nConfigs[pindex].conditions[index][2] = value
    this.setData({
      configs: nConfigs
    })
  },
  onLoad(options) {
    this.initZhibiao(options)
    this.setData({
      options
    })
  },
  addConfig() {
    const config = {
      id: 'mock_' + +new Date(),
      level: this.data?.zhibiaoOptions?.[0]?.value,
      conditions: [
        [this.data?.zhibiaoOptions?.[0]?.value, "eq", "0"]
      ],
      message: ''
    }
    this.setData({
      configs: [...this.data.configs, config]
    })

    wx.pageScrollTo({
      scrollTop: 5000,
      duration: 500
    })
  },
  deleteCondition(e) {
    const id = e?.target?.dataset?.id
    const conditionIndex = e?.target?.dataset?.index
    const index = this.data?.configs?.findIndex(item => item.id == id)
    const nItems = this.data?.configs
    nItems[index].conditions.splice(conditionIndex, 1)
    this.setData({
      configs: nItems
    })
  },
  addCondition(e) {
    const id = e?.target?.dataset?.id;
    const index = this.data?.configs?.findIndex(item => item.id == id)
    const nCondition = [this.data.zhibiaoOptions[0].value, "eq", "0"]

    const nItems = this.data?.configs
    nItems[index].conditions.push(nCondition)
    console.log('nItems', nItems)
    this.setData({
      configs: nItems
    })
  },
  deleteConfig(e) {
    console.log('deleteConfig', e)
    const id = e?.target?.dataset?.id

    const index = this.data?.configs?.findIndex(item => item.id == id)
    console.log('index', id, index)
    const nItems = this.data?.configs
    nItems.splice(index, 1)
    this.setData({
      configs: nItems
    })
    wx.request({
      method: 'DELETE',
      url: `${domain}/api/v1/scene/deleteRule?ruleId=${id}`,
      header: {
        Authorization: wx.getStorageSync('token')
      },
      data: {},
      success: res => {
        if (res?.data?.error === "Unauthorized") {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
      }
    })
  },
  makeConfigs(whenExpr, thenExpr, id) {
    const whenExprObj = JSON.parse(whenExpr)
    const thenExprObj = JSON.parse(thenExpr)

    let config = {
      id
    }
    console.log('thenExprObj', thenExprObj)
    thenExprObj.forEach((item, index) => {
      if (index === 0) {
        const action = item?.actions?.[0]
        config = ({
          id,
          level: action?.device?.metricId,
          controlValue: action?.device?.value?.value === 'on' ? true : false,
        })
      }
    })

    whenExprObj.forEach((item, index) => {
      if (index === 0) {
        const terms = item.terms
        const conditions = []
        terms.forEach(item => {
          conditions.push([item.metricId, item.termType, item.value.value])
        })
        config.conditions = conditions
      }
    })
    return config
  },
  init(options) {
    wx.request({
      url: `${domain}/admin-api/smc/scene/rule?sceneId=${options.id}&type=device`,
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.error === "Unauthorized") {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log(res)
        if (res?.data?.data?.list) {
          const configs = res?.data?.data?.list?.map(item => {
            console.log('item', item)
            const {
              thenExpr,
              whenExpr
            } = item
            item = this.makeConfigs(whenExpr, thenExpr, item.id)
            item.id = item.id
            return item
          })
          console.log('parseCongif', configs)
          this.setData({
            configs
          })
        }
      }
    })
  },
  whenExprAdapter(config) {
    console.log('config', config)
    const terms = config?.conditions?.map(item => {
      const [metricId, termType, value] = item
      return {
        "aggType": "", //多个值时聚合的方式 mean=平均 last=最新（默认） 后面可能要拓展极差()、标准差，检测值不变的情况
        "src": "device", //数据来源
        "sceneId": this.data.options.id,
        metricId,
        "value": {
          "source": "manual", //值类型 manual为人工设定固定值 后续可能有相对值之类的
          value,
        },
        "type": "and", //与前面条件的关系
        termType //判断符号，目前支持的 eq(=)、not(!=)、gt(>)、lt(=)、gte(>=)、lte(<=)、in(枚举包含)、btw(区间内)、nbtw(区间外)
      }
    })

    return {
      "type": "and", //与前面条件的关系
      "termType": "eq",
      "options": [],
      terms
    }
  },
  onChangeControlValue(e) {
    console.log(e)
    const nConfigs = this.data.configs;
    nConfigs[e.currentTarget.dataset.index].controlValue = e.detail.value
    this.setData({
      configs: nConfigs
    })
  },
  alarmAdapter(item) {
    return {
      "parallel": false,
      "actions": [{
        "executor": "device",
        "device": {

          "actionType": "ctrl", //类型  暂固定
          "func": "write", //执行的方法 暂固定
          "sceneId": this.data.options.id, //场景ID
          "metricId": item.level, //指标ID
          "value": {
            "source": "fixed", //值类型 fixed为固定值 后续可能有相对值之类，如调低调高10%
            "value": item.controlValue ? "on" : "off" //根据指标数据类型可能有不同
          },
          "param": "" //其他参数
        },
        "options": {}
      }]
    }
  },
  changeRemark(e) {
    console.log(e)
    const nConfigs = JSON.parse(JSON.stringify(this.data.configs));
    const {
      pindex,
    } = e.currentTarget.dataset
    nConfigs[pindex].message = e.detail.value
    console.log('e.detail.value', e.detail.value)
    this.setData({
      configs: nConfigs
    })
  },
  save() {
    console.log("config", this.data.configs)
    let count = 0
    this.data.configs.forEach(config => {
      const whenExpr = this.whenExprAdapter(config)
      const thenExpr = this.alarmAdapter(config)
      console.log('whenExpr', whenExpr)
      console.log('thenExpr', thenExpr)
      console.log('config', config)

      const data = {
        "name": "自控",
        "type": "device",
        // "level": 0,
        "sceneId": this.data.options.id,
        status: 1,
        // "metricId": 0,
        whenExpr: JSON.stringify([whenExpr]),
        thenExpr: JSON.stringify([thenExpr]),
        "exprFormat": "JSON",
      }
      if ((config?.id + '')?.indexOf('mock_') === -1) {
        data.id = config.id
      }
      console.log('data', data)
      // return
      wx.request({
        method: 'POST',
        url: `${domain}/admin-api/smc/scene/rule`,
        header: {
          Authorization: wx.getStorageSync('token')
        },
        data,
        success: res => {
          if (res?.data?.error === "Unauthorized") {
            wx.removeStorageSync('token')
            wx.reLaunch({
              url: '../login/login',
            })
            return;
          }
          count = count + 1
          console.log(count)
          if (count == this.data.configs.length) {
            wx.showToast({
              title: '保存成功',
            })
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
  },
  // save() {
  //   const whenExpr = this.whenExprAdapter(this.data.configs)
  //   const thenExpr = this.alarmAdapter(this.data.configs)
  //   console.log('whenExpr', whenExpr)
  //   console.log('thenExpr', thenExpr)
  //   wx.request({
  //     method: 'POST',
  //     url: `${domain}/admin-api/smc/scene/rule?sceneId=${this.data.options.id}&type=device`,
  //     header: {
  //       Authorization: wx.getStorageSync('token')
  //     },
  //     data: {
  //       "id": this.data.options.id,
  //       "name": "测试告警",
  //       "type": "device",
  //       "level": 0,
  //       "sceneId": 1,
  //       "metricId": 0,
  //       whenExpr: JSON.stringify(whenExpr),
  //       thenExpr: JSON.stringify(thenExpr),
  //       "exprFormat": "JSON",
  //     },
  //     success: res => {
  //       if (res?.data?.error === "Unauthorized") {
  //         wx.removeStorageSync('token')
  //         wx.reLaunch({
  //           url: '../login/login',
  //         })
  //         return;
  //       }

  //       wx.showToast({
  //         title: '保存成功',
  //       })
  //       // wx.navigateBack({
  //       //   delta: 1
  //       // })
  //     }
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})